package com.zhong.blog.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhong.blog.mapper.BlogMapper;
import com.zhong.blog.pojo.Blog;
import com.zhong.blog.pojo.BlogResp;
import com.zhong.blog.pojo.Tag;
import com.zhong.blog.pojo.User;
import com.zhong.blog.service.BlogService;
import com.zhong.blog.service.TagService;
import com.zhong.blog.service.UserService;
import com.zhong.blog.utlis.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
//@CrossOrigin
public class BlogController {

    @Autowired
    BlogService blogService;
    @Autowired
    BlogMapper blogMapper;
    @Autowired
    TagService tagService;
    @Autowired
    UserService userService;

    @GetMapping("/blog/list")
    @ResponseBody
    public R getBlogList(){
        List<BlogResp> blogResps = new ArrayList<>();
        List<Blog> blogs = blogService.selectList();
        for (Blog blog : blogs) {
            // 查询博客对应的标签
            BlogResp blogResp = new BlogResp();
            String tagId = blog.getTagId();
            String[] ids = tagId.split(",");
            List<String> tagName = new ArrayList<>();
            for (String id : ids) {
                int i = Integer.parseInt(id);
                Tag tag = tagService.selectListById(i);
                tagName.add(tag.getName());
            }
            BeanUtils.copyProperties(blog,blogResp);
            // 查看对应作者
            User author = userService.findById(blog.getUserId());
            if (author != null){
                blogResp.setBlogAuthor(author.getUsername());
            }else {
                blogResp.setBlogAuthor("查无此人");
            }
            blogResp.setTagName(tagName);
            blogResps.add(blogResp);
        }
        // 查询所有标签
        List<Tag> tags = tagService.selectList();

        return R.ok().put("blogs",blogResps).put("tags",tags);
    }


    @PostMapping("/blog/listbypage")
    @ResponseBody
    public R getBlogListByPage(@RequestParam("page") int current, @RequestParam("size") int size){
//        System.out.println("当前页："+current);
//        System.out.println("大小："+size);

        List<BlogResp> blogResps = new ArrayList<>();

        Page<Blog> page = new Page<>(current,size);
        blogMapper.selectPage(page,null);
        for (Blog record : page.getRecords()) {
            // 查询博客对应的标签
            BlogResp blogResp = new BlogResp();
            String tagId = record.getTagId();
            if (tagId == null){
                tagId="1";
            }
            String[] ids = tagId.split(",");
            List<String> tagName = new ArrayList<>();
            for (String id : ids) {
                int i = Integer.parseInt(id);
                Tag tag = tagService.selectListById(i);
                tagName.add(tag.getName());
            }
            BeanUtils.copyProperties(record,blogResp);
            blogResp.setTagName(tagName);
            blogResps.add(blogResp);
        }
        long total = page.getTotal();
        for (BlogResp resp : blogResps) {
            System.out.println(resp.getTagName());
        }
        // 查询包含的所有标签
        List<Tag> tags = tagService.selectList();
        return R.ok().put("blogs",blogResps).put("total",total).put("tags",tags);
    }

    @PostMapping("/blog/editSubmit")
    public R saveBlog(@RequestBody @Valid Blog blog, BindingResult bindingResult){
        System.out.println(blog.toString());
        String tagId = blog.getTagId();

        //  数据校验
        if (bindingResult.hasErrors()){
            System.out.println("校验错误");
            Map<String,String> map=new HashMap<>();
            bindingResult.getFieldErrors().forEach((item)->{
                String message = item.getDefaultMessage();
                String field = item.getField();
                map.put(field,message);
            });
            System.out.println(map.toString());
            return R.error(400,"提交数据不合法").put("err",map.toString());
        }
        // 处理tag
        tagId = tagId.replace("[", "");
        tagId = tagId.replace("]","");
        System.out.println(tagId);
        blog.setTagId(tagId);
        blogService.save(blog);
        return R.ok();
    }
    @PostMapping("/blog/tag")
    public R queryTag(){
        List<Tag> tags = tagService.selectList();
        return R.ok().put("tags",tags);
    }
    @PostMapping("/blog/like")
    public R like(@RequestBody Blog blog){
        System.out.println(blog.toString());
        int count = blogService.updata(blog);
        System.out.println("是否更新成功："+count);
        return R.ok();
    }
    @GetMapping("/blog/search")
    public R search(@RequestParam("key") String key){
        List<Blog> blogs = blogService.selectListByKey(key);

        return R.ok().put("blogs",blogs);
    }

}
